using System;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using EPiAbstractions;
using EPiServer.Common.Queries;
using EPiServer.Community.Blog;
using EPiServer.Community.Blog.Queries;
using EPiServer.Core;
using EPiServer.SpecializedProperties;
using JoelAbrahamsson.BlogExtensions;
using JoelAbrahamsson.PageTypes;
using JoelAbrahamsson.Web.Common;
using log4net;

namespace JoelAbrahamsson.Web.Controllers
{
    public class ErrorController : Controller
    {
        ExtendedBlogHandlerFacade blogHandlerFacade;
        IDataFactoryFacade dataFactoryFacade;
        private ILog errorLog;

        public ErrorController(ExtendedBlogHandlerFacade blogHandlerFacade, IDataFactoryFacade dataFactoryFacade, ILog errorLog)
        {
            this.blogHandlerFacade = blogHandlerFacade;
            this.dataFactoryFacade = dataFactoryFacade;
            this.errorLog = errorLog;
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ViewResult Unknown()
        {  
            Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            return View();

        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult NotFound(string aspxerrorpath)
        {
            if (!string.IsNullOrEmpty(aspxerrorpath))
            {
                EntryQuery query = new EntryQuery();
                StringCriterion oldUrlCriterion = new StringCriterion();
                oldUrlCriterion.Value = aspxerrorpath;
                query["OldUrls"] = oldUrlCriterion;
                EntryCollection matchingEntries = blogHandlerFacade.GetQueryResult(query);
                try
                {
                    if (matchingEntries.Count > 0 && matchingEntries[0] != null)
                        return new PermanentRedirectResult(matchingEntries[0].GetUrl(ControllerContext.RequestContext));
                }
                catch (NullReferenceException)
                {

                }
            }

            Start startPage = (Start) dataFactoryFacade.GetPage(PageReference.StartPage);
            if (startPage.OldUrlMappings != null)
            {
                LinkItem matchingItem =
                    startPage.OldUrlMappings.Where(link => link.Text.Equals(aspxerrorpath, StringComparison.InvariantCultureIgnoreCase)).
                        FirstOrDefault();
                if (matchingItem != default(LinkItem))
                {
                    string redirectUrl = matchingItem.Title;
                    if(string.IsNullOrEmpty(redirectUrl))
                        redirectUrl = matchingItem.ToMappedLink();

                    return new PermanentRedirectResult(redirectUrl);
                }
            }

            errorLog.Warn("404: " + aspxerrorpath);

            Response.StatusCode = (int)HttpStatusCode.NotFound;

            ViewData["aspxerrorpath"] = aspxerrorpath;
            return View();

        }
    }
}
